<template>
  <div class="notification-badge">
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-icon">
      <el-button
        link
        icon="el-icon-bell"
        @click="showNotificationDropdown"
        class="notification-button"
      />
    </el-badge>
    
    <!-- 消息下拉菜单 -->
    <el-dropdown
      ref="notificationDropdown"
      trigger="click"
      placement="bottom-end"
      :show-timeout="0"
      :hide-timeout="0"
      @command="handleNotificationCommand"
    >
      <span class="el-dropdown-link">
        <el-badge :value="unreadCount" :hidden="unreadCount === 0">
          <el-button icon="el-icon-bell" />
        </el-badge>
      </span>
      
      <template #dropdown>
        <el-dropdown-menu class="notification-dropdown">
          <div class="dropdown-header">
            <span class="header-title">消息通知</span>
            <el-button
              v-if="unreadCount > 0"
              link
              size="small"
              @click="markAllAsRead"
            >
              全部已读
            </el-button>
          </div>
          
          <div class="notification-list">
            <div v-if="loading" class="loading-item">
              <el-skeleton :rows="2" animated />
            </div>
            
            <div v-else-if="recentNotifications.length === 0" class="empty-item">
              <el-empty description="暂无消息" :image-size="60" />
            </div>
            
            <div v-else>
              <div
                v-for="notification in recentNotifications"
                :key="notification.id"
                class="notification-item"
                :class="{ 'unread': !notification.is_read }"
                @click="viewNotification(notification)"
              >
                <div class="notification-icon">
                  <el-avatar :size="32" :src="getNotificationIcon(notification.type)" />
                </div>
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
                </div>
                <div class="notification-actions">
                  <el-button
                    v-if="!notification.is_read"
                    @click.stop="markAsRead(notification.id)"
                    link
                    size="mini"
                  >
                    已读
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="dropdown-footer">
            <el-button @click="goToMessageCenter">
              查看全部消息
            </el-button>
          </div>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script>
import { useNotificationsStore } from '@/store/modules/notifications';

export default {
  name: 'NotificationBadge',
  
  data() {
    return {
      loading: false,
      showDropdown: false
    };
  },
  
  computed: {
    // 使用Pinia store
    notificationsStore() {
      return useNotificationsStore();
    },
    
    notifications() {
      return this.notificationsStore.notifications;
    },
    
    unreadCount() {
      return this.notificationsStore.unreadCount;
    },
    
    loading() {
      return this.notificationsStore.loading;
    },
    
    // 获取最近的消息（最多显示5条）
    recentNotifications() {
      return this.notifications.slice(0, 5);
    }
  },
  
  mounted() {
    this.notificationsStore.loadNotifications();
    this.notificationsStore.loadUnreadCount();
    
    // 定期刷新未读消息数量
    this.startPolling();
  },
  
  beforeUnmount() {
    this.stopPolling();
  },
  
  methods: {
    
    // 显示消息下拉菜单
    showNotificationDropdown() {
      this.$refs.notificationDropdown.handleOpen();
    },
    
    // 处理消息命令
    handleNotificationCommand(command) {
      switch (command) {
        case 'view-all':
          this.goToMessageCenter();
          break;
        case 'mark-all-read':
          this.markAllAsRead();
          break;
      }
    },
    
    // 查看消息详情
    viewNotification(notification) {
      // 如果消息未读，自动标记为已读
      if (!notification.is_read) {
        this.markAsRead(notification.id);
      }
      
      // 显示消息详情对话框
      this.$emit('view-notification', notification);
    },
    
    // 标记消息为已读
    async markAsRead(notificationId) {
      try {
        await this.notificationsStore.markAsRead(notificationId);
        this.$message.success('已标记为已读');
      } catch (error) {
        this.$message.error('操作失败');
      }
    },
    
    // 全部标记为已读
    async markAllAsRead() {
      try {
        await this.notificationsStore.markAllAsRead();
        this.$message.success('已全部标记为已读');
      } catch (error) {
        this.$message.error('操作失败');
      }
    },
    
    // 跳转到消息中心
    goToMessageCenter() {
              this.$router.push('/use/messages');
    },
    
    // 获取消息图标
    getNotificationIcon(type) {
      const iconMap = {
        resume_review: '/icons/resume-review.png',
        application_recommend: '/icons/application-recommend.png',
        enterprise_contact: '/icons/enterprise-contact.png',
        password_change: '/icons/password-change.png',
        system_notification: '/icons/system-notification.png'
      };
      return iconMap[type] || iconMap.system_notification;
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      
      if (diff < 60000) { // 1分钟内
        return '刚刚';
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`;
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`;
      } else {
        return date.toLocaleDateString();
      }
    },
    
    // 开始轮询
    startPolling() {
      this.pollingInterval = setInterval(() => {
        this.notificationsStore.loadUnreadCount();
      }, 30000); // 每30秒检查一次
    },
    
    // 停止轮询
    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval);
        this.pollingInterval = null;
      }
    }
  }
};
</script>

<style scoped>
.notification-badge {
  position: relative;
  display: inline-block;
}

.notification-button {
  font-size: 18px;
  color: #606266;
}

.notification-button:hover {
  color: #409eff;
}

.notification-dropdown {
  width: 320px;
  max-height: 400px;
  overflow: hidden;
}

.dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.header-title {
  font-weight: 600;
  color: #303133;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
}

.loading-item {
  padding: 16px;
}

.empty-item {
  padding: 20px;
  text-align: center;
}

.notification-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #e6f7ff;
}

.notification-item.unread:hover {
  background-color: #bae7ff;
}

.notification-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-actions {
  margin-left: 8px;
  flex-shrink: 0;
}

.dropdown-footer {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
  background: #fafafa;
}

/* 自定义滚动条 */
.notification-list::-webkit-scrollbar {
  width: 4px;
}

.notification-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.notification-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.notification-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-dropdown {
    width: 280px;
  }
  
  .notification-item {
    padding: 10px 12px;
  }
  
  .notification-title {
    font-size: 13px;
  }
}

/* 自定义按钮样式 */
.el-button {
  border: none;
  background: transparent;
}

.el-button:hover {
  border: none;
  background-color: #ecf5ff;
}

.dropdown-footer .el-button {
  color: #409EFF;
  padding: 4px 8px;
}

.dropdown-footer .el-button:hover {
  color: #337ecc;
}
</style> 